package com.yaocw.baseproject.fragment;

import android.Manifest;
import android.content.DialogInterface;
import android.content.Intent;
import android.content.pm.PackageManager;
import android.graphics.Bitmap;
import android.net.Uri;
import android.os.Build;
import android.os.Environment;
import android.provider.MediaStore;
import android.view.LayoutInflater;
import android.view.View;
import android.widget.Button;
import android.widget.ImageView;

import androidx.appcompat.app.AlertDialog;
import androidx.core.app.ActivityCompat;
import androidx.core.content.ContextCompat;
import androidx.core.content.FileProvider;

import com.google.zxing.BarcodeFormat;
import com.google.zxing.EncodeHintType;
import com.google.zxing.WriterException;
import com.google.zxing.common.BitMatrix;
import com.google.zxing.integration.android.IntentIntegrator;
import com.google.zxing.qrcode.QRCodeWriter;
import com.yaocw.baseproject.R;
import com.yaocw.baseproject.activity.QrCodeCaptureActivity;

import java.io.File;
import java.io.IOException;
import java.util.HashMap;
import java.util.Map;

public class MineFragment extends BaseFragment {

    public static final int SCAN_QR_CODE = 1;
    public static final int FETCH_WRITE_AUTH_FOR_CAMERA = 2;
    public static final int FETCH_WRITE_AUTH_FOR_ALBUM = 3;
    public static final int PICK_PHOTO = 4;
    public static final int CAPTURE_PHOTO = 5;

    private Button btnScan;
    private Button btnGenerateQrcode;
    private Button btnCapture;
    private Button btnPickImages;

    public static Uri captureImageUri;
    public static final String captureOutputPath = Environment.getExternalStorageDirectory() + File.separator + "capture_output_image.jpg";

    public static MineFragment newInstance() {
        MineFragment fragment = new MineFragment();
        return fragment;
    }

    @Override
    protected int initLayout() {
        return R.layout.fragment_mine;
    }

    @Override
    protected void initView() {
        btnScan = mRootView.findViewById(R.id.btn_scan_qrcode);
        btnScan.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                new IntentIntegrator(getActivity())
                        .setDesiredBarcodeFormats(IntentIntegrator.ALL_CODE_TYPES)// 扫码的类型,可选：一维码，二维码，一/二维码
                        .setRequestCode(SCAN_QR_CODE)
                        .setPrompt("请对准二维码")// 设置提示语
                        .setCameraId(0)// 选择摄像头,可使用前置或者后置
                        .setBeepEnabled(true)// 是否开启声音,扫完码之后会"哔"的一声
                        .setCaptureActivity(QrCodeCaptureActivity.class)
                        .initiateScan();// 初始化扫码
            }
        });

        btnGenerateQrcode = mRootView.findViewById(R.id.btn_generate_qrcode);
        btnGenerateQrcode.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                AlertDialog.Builder customizeDialog =
                        new AlertDialog.Builder(mRootView.getContext());

                final View dialogView = LayoutInflater.from(mRootView.getContext())
                        .inflate(R.layout.dialog_show_image, null);
                ImageView ivShow = dialogView.findViewById(R.id.iv_show);
                ivShow.setImageBitmap(generateBitmap("Hello Qrcode", 600, 600));

                customizeDialog.setTitle("二维码");
                customizeDialog.setView(dialogView);
                customizeDialog.setPositiveButton("关闭", new DialogInterface.OnClickListener() {
                    @Override
                    public void onClick(DialogInterface dialog, int which) {
                        showToast("已关闭二维码页面");
                    }
                });
                customizeDialog.show();
            }
        });

        btnCapture = mRootView.findViewById(R.id.btn_capture);
        btnCapture.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                requestPermission(FETCH_WRITE_AUTH_FOR_CAMERA);
            }
        });

        btnPickImages = mRootView.findViewById(R.id.btn_pick_images);
        btnPickImages.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                requestPermission(FETCH_WRITE_AUTH_FOR_ALBUM);
            }
        });
    }

    @Override
    protected void initData() {

    }

    /**
     * 生成固定大小的二维码(不需网络权限)
     *
     * @param content 需要生成的内容
     * @param width   二维码宽度
     * @param height  二维码高度
     * @return
     */
    private Bitmap generateBitmap(String content, int width, int height) {
        QRCodeWriter qrCodeWriter = new QRCodeWriter();
        Map<EncodeHintType, String> hints = new HashMap<>();
        hints.put(EncodeHintType.CHARACTER_SET, "utf-8");
        try {
            BitMatrix encode = qrCodeWriter.encode(content, BarcodeFormat.QR_CODE, width, height, hints);
            int[] pixels = new int[width * height];
            for (int i = 0; i < height; i++) {
                for (int j = 0; j < width; j++) {
                    if (encode.get(j, i)) {
                        pixels[i * width + j] = 0x00000000;
                    } else {
                        pixels[i * width + j] = 0xffffffff;
                    }
                }
            }
            return Bitmap.createBitmap(pixels, 0, width, width, height, Bitmap.Config.RGB_565);
        } catch (WriterException e) {
            e.printStackTrace();
        }

        return null;
    }

    private void requestPermission(int type) {
        if (ContextCompat.checkSelfPermission(mRootView.getContext(), Manifest.permission.WRITE_EXTERNAL_STORAGE) != PackageManager.PERMISSION_GRANTED) {
            ActivityCompat.requestPermissions(getActivity(), new String[]{Manifest.permission.WRITE_EXTERNAL_STORAGE}, type);
        } else {
            fetchPhoto(type);
        }
    }

    private void fetchPhoto(int type) {
        if (type == FETCH_WRITE_AUTH_FOR_CAMERA) {
            File outputImage = new File(captureOutputPath);
                /*
                创建一个File文件对象，用于存放摄像头拍下的图片，我们把这个图片命名为output_image.jpg
                并把它存放在应用关联缓存目录下，调用getExternalCacheDir()可以得到这个目录，为什么要
                用关联缓存目录呢？由于android6.0开始，读写sd卡列为了危险权限，使用的时候必须要有权限，
                应用关联目录则可以跳过这一步
                 */
            try//判断图片是否存在，存在则删除在创建，不存在则直接创建
            {
                if (!outputImage.getParentFile().exists()) {
                    outputImage.getParentFile().mkdirs();
                }
                if (outputImage.exists()) {
                    outputImage.delete();
                }

                outputImage.createNewFile();

                if (Build.VERSION.SDK_INT >= 24) {
                    captureImageUri = FileProvider.getUriForFile(mRootView.getContext(),
                            "com.example.mydemo.fileprovider", outputImage);
                } else {
                    captureImageUri = Uri.fromFile(outputImage);
                }

                Intent intent = new Intent(MediaStore.ACTION_IMAGE_CAPTURE);
                intent.putExtra(MediaStore.EXTRA_OUTPUT, captureImageUri);
                getActivity().startActivityForResult(intent, CAPTURE_PHOTO);
            } catch (IOException e) {
                e.printStackTrace();
            }
        } else {

            Intent intent = new Intent(Intent.ACTION_GET_CONTENT);
            intent.setType("image/*");
            getActivity().startActivityForResult(intent, PICK_PHOTO);
        }
    }
}
